package com.rzico.sbl.ui.report.depot

import android.view.View
import android.widget.LinearLayout
import android.widget.TextView
import androidx.core.view.isVisible
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityReportDepotOutBinding
import com.rzico.sbl.model.DepotOutData
import com.rzico.sbl.ui.report.other.ReportUrl
import com.rzico.sbl.ui.report.other.goToOrderDetail
import com.rzico.sbl.viewmodel.ReportDepotViewModel
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.xinnuo.common.extend.find
import com.xinnuo.common.extend.get
import com.xinnuo.common.extend.gone
import com.xinnuo.common.extend.inflate
import com.xinnuo.common.extend.oneClick
import com.xinnuo.common.extend.visible
import com.xinnuo.common.extend.visibleValue
import com.xinnuo.common.helper.getTimeString
import com.xinnuo.common.helper.intValue
import com.xinnuo.common.listener.onTabSelectedListener
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.common_ui.base.count
import com.xinnuo.common_ui.base.loadLinear
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.showHintDialog
import com.xinnuo.common_ui.utils.subscribeBySuccess
import com.xinnuo.slimadapter.SlimAdapter

class ReportDepotOutActivity : BaseActivity(R.layout.activity_report_depot_out) {

    private val mBinding by lazy { ActivityReportDepotOutBinding.bind(getRootView()) }

    private var mStatus = ""

    override fun getViewModel() = get<ReportDepotViewModel>()

    override fun initData() {
        initTitle(title = "出库")

        initLayout()
        initTabLayout()
    }

    private fun initLayout() {
        mBinding
            .listLayout
            .apply {
                emptyLayout.also {
                    it.emptyHint.text = "暂无相关出库信息！"
                }

                recycleList.also { view ->
                    view.loadLinear(
                        refresh = swipeRefresh,
                        onRefresh = { getData(0) },
                        onLoad = {
                            if (!isLoadingMore) {
                                isLoadingMore = true
                                getData(pageNum)
                            }
                        }
                    )

                    view.addItemDecoration(SpaceTBDecoration(hasHeader = false))

                    mAdapter = SlimAdapter.creator()
                        .register<DepotOutData>(R.layout.item_report_depot_out) { jector, bean, index ->
                            jector.apply {
                                gone(R.id.item_depot_btn2)
                                text(
                                    R.id.item_depot_name,
                                    if (bean.method == "1") "" else bean.name
                                )
                                text(
                                    R.id.item_depot_time,
                                    when (mStatus) {
                                        "unconfirmed" -> "创建时间: ${bean.createDate.getTimeString()}"
                                        "debit" -> "出库时间: ${bean.debitDate.getTimeString()}"
                                        else -> ""
                                    }
                                )
                                text(
                                    R.id.item_depot_total,
                                    bean.productList.sumOf { it.quantity.intValue }.toString()
                                )
                                text(
                                    R.id.item_depot_status,
                                    if (bean.method == "1") "水站自提" else ""
                                )
                                text(
                                    R.id.item_depot_hint,
                                    if (bean.method == "1") "" else "司机："
                                )

                                visibility(
                                    R.id.item_depot_bottom,
                                    visibleValue { mStatus == "unconfirmed" }
                                )

                                with<LinearLayout>(R.id.item_depot_content) { layout ->
                                    layout.removeAllViews()

                                    bean.productList.forEach {
                                        layout.addView(
                                            inflate<View>(R.layout.content_report_depot_hint).apply {
                                                find<TextView>(R.id.conent_title).text = it.name
                                                find<TextView>(R.id.conent_num).text = it.quantity
                                            }
                                        )
                                    }
                                }

                                with<LinearLayout>(R.id.item_depot_sn) { layout ->
                                    layout.removeAllViews()

                                    bean.snList.forEach { item ->
                                        layout.addView(
                                            inflate<View>(R.layout.content_report_depot_station_title).apply {
                                                find<TextView>(R.id.conent_title).apply {
                                                    text = "${item.name}(${item.sn})："

                                                    oneClick {
                                                        goToOrderDetail("orderSn" to item.sn)
                                                    }
                                                }
                                            }
                                        )

                                        item.itemList.forEach {
                                            layout.addView(
                                                inflate<View>(R.layout.content_report_depot_hint).apply {
                                                    find<View>(R.id.conent_space).visible = true
                                                    find<TextView>(R.id.conent_title).text = it.name
                                                    find<TextView>(R.id.conent_num).text =
                                                        it.quantity
                                                }
                                            )
                                        }
                                    }
                                }

                                clicked(R.id.item_depot_btn1) {
                                    groupConfirm(bean.id, index)
                                }
                            }
                        }
                        .attachTo(view)
                }
            }
    }

    /**
     * 初始化 TabLayout
     */
    private fun initTabLayout() {
        mBinding
            .depotTab
            .apply {
                onTabSelectedListener {
                    onTabSelected {
                        it?.let {
                            mStatus = when (it.position) {
                                0 -> "unconfirmed"
                                1 -> "debit"
                                else -> ""
                            }

                            getViewModel().cancelRequest()
                            getViewModel().delay { updateList() }
                        }
                    }
                }

                addTab(this.newTab().setText("待出库"), true)
                addTab(this.newTab().setText("已出库"), false)
            }
    }

    /**
     * 成品出库
     */
    private fun groupConfirm(groupId: String, index: Int) {
        showHintDialog(
            title = "成品出库",
            hint = "确定要执行出库操作吗？",
            onSure = {
                getViewModel()
                    .requestBind(
                        requestUrl = ReportUrl.getBaseUrl().depotSure,
                        params = arrayOf("id" to groupId)
                    )
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("出库成功！")

                            mList.removeAt(index)
                            mAdapter.apply {
                                notifyItemRemoved(index)
                                notifyItemRangeChanged(index, mList.size - index)
                            }

                            mBinding
                                .listLayout
                                .emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                    )
            }
        )
    }

    /**
     * 库管出库合并单列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .outList(
                page = index,
                status = mStatus,
                onSuccess = {
                    mList.apply {
                        if (index == 0) {
                            clear()
                            pageNum = 0
                        }
                        addItems(it)
                        if (it.count() > 0) pageNum++
                    }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        if (mList.isNotEmpty()) {
            mList.clear()
            mAdapter.notifyDataSetChanged()
        }

        getData(0)
    }

}